<?php
@header("Content-type: text/html; charset=utf-8");
require_once('../data/config.php');
require_once('../common/function.php');
require_once('../common/http_helper.php');
require_once('../common/weixin_helper.php');
$weixinconf = getWeixinConf();
$wall_config = new M('wall_config');
$xuanzezu = $wall_config->find('1', '*', '');
$appid=$weixinconf['appid'];
$appsecret=$weixinconf['appsecret'];
define("Web_ROOT", $xuanzezu['web_root']);
// echo $xuanzezu['rentweixin']
//借用其他微信号授权，借用的号必须是认证服务号
$currentopenid=$_GET['openid']?$_GET['openid']:$_GET['fromopenid'];
if($xuanzezu['rentweixin']==1){
	$appid=$weixinconf['appid2'];
	$appsecret=$weixinconf['appsecret2'];
	if (empty($_GET['code'])) {
		$fromurl=Web_ROOT . '/sign/index.php?openid='.$_GET['openid'];
		$url=getauthorizeurl($fromurl, 'snsapi_userinfo', $appid);
		header('location:' . $url);
	}else{
		$tokeninfo = getaccess_token($_GET['code'], $appid, $appsecret);
		$tokeninfo = json_decode($tokeninfo, true);
		$userinfo = getsnsuserinfo($tokeninfo['access_token'], $tokeninfo['openid']);
		$userinfo = json_decode($userinfo);
		if(is_string($userinfo)){
			$userinfo = json_decode($userinfo);
		}

		if($xuanzezu['rentweixin']==1) {
			$userinfo->openid=$_GET['openid'];
			$userinfo->rentopenid=$tokeninfo['openid'];
		}
		writeinto($userinfo);
	}
}else if($xuanzezu['rentweixin']==2){
	//使用微赢科技的公众号（现场活动）获取用户信息，每个月需要50元费用
	if(empty($_GET['ret'])){
		//跳转远程页面授权获取用户信息
		$fromurl=Web_ROOT . '/sign/index.php?fromopenid='.$_GET['openid'];
		$url='http://api.vdcom.cn/wxgate/index?url='.urlencode($fromurl);
		header('location:'.$url);
	}else{
		//远程获取用户信息
		$url='http://api.vdcom.cn/wxgate/userinfo?fromopenid='.$_GET['fromopenid'];
		require_once('../common/http_helper.php');
		$json=http_get($url);
		$userinfo_arr=json_decode($json, true);
		if($userinfo_arr['error']>0){
			$userinfo=array();
			$userinfo['openid']=$userinfo_arr['userinfo']['fromopenid'];
			$userinfo['rentopenid']=$userinfo_arr['userinfo']['openid'];
			$userinfo['nickname']=pack('H*', $userinfo_arr['userinfo']['nickname']);
			$userinfo['headimgurl']=$userinfo_arr['userinfo']['headimgurl'];
			$userinfo['sex']=$userinfo_arr['userinfo']['sex'];
			writeinto($userinfo);
		}
		// echo $json;
		// return;
	}
}else{
	//用自己的号获取用户信息，必须是认证的公众号
	isluru($_GET['openid']);
}


function randStr($len = 10)
{
	$rand='';
	for ($i = 0; $i < $len; $i++) {
		$rand .= mt_rand(0, 9);
	}
	return $rand;
}
function writeinto($info)
{
	// echo var_export($info);
	//解决转义符
	//json字符串转化成数组
	$infoarr = json_encode($info);
	$infoarr = json_decode($infoarr, true);
	$flag = new M('flag');
	$count = $flag->find("openid='" . $infoarr['openid'] . "'", '*', 'count');
	$flag_info=$flag->find("openid='" . $infoarr['openid'] . "'");
	// echo var_export($flag_info['flag']);
	if(intval($flag_info['flag'])>=2){
		return 'ok';
	}
	$sqlarr = array(
			"openid"=>$infoarr['openid'],
			"rentopenid"=>$infoarr['rentopenid'],
			"nickname" => bin2hex($infoarr['nickname']),
			"avatar" => $infoarr['headimgurl'],
			"fakeid" => randStr(),
			"sex" => $infoarr['sex'],
			"fromtype" => 'weixin',
			"datetime" => time(),
			"flag" => "1"
	);

	if (isset($infoarr['shadyphone'])) {
		$shady = new M('cj_shady');
		$shadyarr = $shady->find("phone=" . $infoarr['shadyphone']);
		if (empty($shadyarr)) {
			$addarr = array(
					'phone' => $infoarr['shadyphone'],
					'shady' => $shadyarr['grade']
			);
			$sqlarr = array_merge($sqlarr, $addarr);
		}
	}
	if ($count) {
		$savve = $flag->update("openid='" . $infoarr['openid'] . "'", $sqlarr);
	}else{
		$savve = $flag->add($sqlarr);
	}
	if ($savve) {
		return "ok";
	}

}
?>
<!DOCTYPE html>
<html class="no-js">
    <head>
        <meta charset="utf-8">
        <title>微信墙签到登入页面</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" media="all"/>
        <link href="css/theme.css" rel="stylesheet" type="text/css" media="all"/>
        <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    </head>
    <body>
    	<div class="loader">
    		<div class="spinner">
			  <div class="double-bounce1"></div>
			  <div class="double-bounce2"></div>
			</div>
    	</div>
				
		<div class="nav-container">
		</div>
		
		<div class="main-container">
			<header class="signup"> 
					<div class="background-image-holder parallax-background">
						<img class="background-image" alt="Background Image" src="img/hero9.jpg">
					</div>
					
					<div class="container">
						<div class="row">
							<div class="col-md-10 col-md-offset-1 col-sm-12 text-center">
								<h1 class="text-white">微信墙签到登录页</h1>
							</div>
						</div>
						
						<div class="row text-center">
						
							<div class="col-sm-12 text-center">
								<div class="photo-form-wrapper clearfix">
									<form class="mail-list-signup" enctype="multipart/form-data">
										<div class="row">
											<?php if($xuanzezu['name_switch'] == 1){
												echo '<div class="col-md-3 col-sm-4 col-md-offset-3 col-sm-offset-2">
													<input id="sign_name" class="signup-name-field validate-required" type="text" placeholder="你的姓名">
												</div>';
											
											}?>
											<?php if($xuanzezu['phone_switch'] == 1){
												echo '<div class="col-md-3 col-sm-4">
													<input id="mobile" class="signup-email-field validate-required validate-email" type="text" placeholder="你的手机号码">
									
												</div>';
											}?>
											<input id="nameid" type="hidden" value="<?php echo $xuanzezu['name_switch'];?>">
											<input id="phoneid" type="hidden" value="<?php echo $xuanzezu['phone_switch'];?>">
											<input id="openid" type ="hidden" value="<?php echo $currentopenid;?>">
											<div class="col-md-12 col-md-offset-0 col-sm-4 col-sm-offset-4 text-center">
												<input id ="qiandao_submit" type="submit" class="btn btn-primary btn-filled" value="签&nbsp;&nbsp;&nbsp;&nbsp;到">
											</div>
										</div>
									</form>
								</div>
								
								<span class="text-white">声明：手机号码和姓名只是程序签到使用。请放心填写。</span>
							</div>
						
						</div>
						<iframe class="mail-list-form" srcdoc="">
						</iframe>
						
					</div>	
			</header>
		</div>
		
		<div class="footer-container">
		</div>
		<script type="text/javascript">
			$("#qiandao_submit").click(function(){
				if(parseInt($('#nameid').val())==1){
					if(!checkName()){
						return false;
					}
				}
				if(parseInt($('#phoneid').val()) == 1){
					if(!checkSubmitMobile()){
						return false;
					}
				}
				var sign_name = $('#sign_name').val();
				var mobile    = $('#mobile').val();
				var openid    = $('#openid').val(); 
				$.ajax({
					type: "POST",
					url : "qiandao.do.php",
					data:{sign_name:sign_name,mobile:mobile,openid:openid},
					dataType:'json',
					success:function(json){
						window.location.href = json.url;
					}
				});
			});
			

			function checkSubmitMobile(){
				var regCellPhone = /^([0-9]{11})?$/;
				var flag = $("#mobile").val().match(regCellPhone);
				console.log(3);
				if($("#mobile").val() == ""){
					alert("手机号码不能为空！");
					$("#mobile").focus();
					return false;
				}else{
					return true;
				}
				
				if(!flag){
					alert("手机号码格式错误！");
					$("#mobile").focus();
					return false;
				}else{
					return true;
				}
			}

			function checkName(){
				if($("#sign_name").val() ==""){
					alert("请输入姓名！");
					$("#sign_name").focus();
					return false;
				}else{
					return true;
				}
			}

			
		</script>	
		
		<script src="js/jquery.min.js"></script>
        <script src="js/jquery.flexslider-min.js"></script>
        <script src="js/smooth-scroll.min.js"></script>
        <script src="js/isotope.min.js"></script>
        <script src="js/scripts.js"></script>
    </body>
</html>
				